package generator;
// Based on project found at: https://github.com/Clairette/sudoku/

public class Solver
{
	private Board board;
	private boolean generated;
	
	public Solver(Board board)
	{
		this.board = board;
		this.generated = false;
	}
	
	public Solver(Board board, boolean generated)
	{
		this.board = board;
		this.generated = generated;
	}
	
	public Board getBoard()
	{
		return this.board;
	}
	
	public boolean solveBoard()
	{
		return solveBoard(0, 0, 1);
	}
	
	private boolean solveBoard(int col, int row, int number)
	{
		if (col == 9 && row == 0)
		{
			// if at end of board, puzzle solved
			return true;
		}
		else
		{
			if (board.getCell(col, row) != null && board.getCell(col, row).equals(0))
			{
				// if the cell is empty
				while (number <= 9)
				{
					if (board.contains(col, row, number))
					{
						// find the first possible number for the cell
						number++;
					}
					else
					{
						// set the cell to this number
						board.setCell(col, row, number, generated);
						if (solveBoard(next(col, row)[0], next(col, row)[1], 1))
						{
							// if the board is solvable with this number, return true
							board.setCell(col, row, number, generated);
							return true;
						}
						else
						{
							// if not, try the next possible number for the cell
							board.setCell(col, row, 0, generated);
							return solveBoard(col, row, number + 1);
						}
					}
				}
				// if no possible numbers lead to a solution, return false
				return false;
			}
			else
			{
				// if not, go to the next cell
				return solveBoard(next(col, row)[0], next(col, row)[1], 1);
			}
		}
	}
	
	private int[] next(int i, int j)
	{
		int[] next = new int[2];
		
		j += 1;
		if (j > 8)
		{
			i += 1;
			j = 0;
		}
		
		next[0] = i;
		next[1] = j;
		return next;
	}
}